const fs = require('fs');
const request = require('request');
const compressing = require('compressing');
const path = require('path');


const downFile = async(name,array,route) => {
  // 例： /\/axios-.+tgz$/
  const re = new RegExp(`\/${name}-.+tgz`, 'g')
  const arr = typeof array === 'string' ? JSON.parse(array) : array;
  const paths = `${path.resolve(__dirname,'..')}/public`;
  for( item of arr){
    // 下载文件
    await new Promise ((res,rej) => {
      const src = route.replace(re,`/${name}-${item}.tgz`).replace('npmjs.org','cnpmjs.org');
      request(src,(error,respost,data) => {
        if(error){
          console.log('下载失败')
          res();
          return false
        }
        console.log('\033[32m SUCCESS: 正在下载'+src+' \033[39m');
        compressing.tgz.uncompress(`./public/${name}/${item}/${item}.tgz`, `./public/${name}/${item}`).then(() => {
          console.log('\033[32m SUCCESS: '+name+'解压成功 \033[39m');
          res();
        }).catch(e => {
          console.log(`./public/${name}/${item}/${item}.tgz`);
          console.log('\033[31m ERROR: '+name+'解压失败 \033[39m');
          res();
        });
      }).pipe(fs.createWriteStream(`./public/${name}/${item}/${item}.tgz`));
    })
  }
  // 移动文件
  arr.forEach(item => {
    fs.access(`./public/${name}/${item}/package/dist/${name}.js`, (err) => {
      if(err){
        console.log('\033[31m ERROR: ./public/'+name+'/'+item+'/package/dist/'+name+'.js找不到文件 \033[39m');
        return false;
      }
      try{
        fs.renameSync(`${paths}/${name}/${item}/package/dist/${name}.js`, `${paths}/${name}/${item}/${name}.js`);
        fs.renameSync(`${paths}/${name}/${item}/package/dist/${name}.min.js`, `${paths}/${name}/${item}/${name}.min.js`);
      }
      catch(err){
        console.log('\033[31m ERROR: 移动'+paths+'/'+name+'/'+item+'/package/dist/'+name+'.js时报错 \033[39m');
      }
    });
  });
  console.log('全部完成');
}
const fileDownExports = (name,array,route) => {
  downFile(name,array,route)
}

module.exports = fileDownExports;

